package handler

import (
	"encoding/json"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"

	"ssforward/common/constant"
	"ssforward/common/enums"
	mq "ssforward/common/middleware/mqtt"
	"ssforward/common/utils"
	"ssforward/internal/data/clients"
)

type MqttForwardHandler struct {
	Orm *gorm.DB
}

// 固定一个主题
var forwardTopic = "/sansan/data/forward"

func (e *MqttForwardHandler) ForwardData(ruleConfig map[string]interface{}, jsonData map[string]interface{}) {
	serverId, ok := ruleConfig["serverId"]
	if !ok || serverId == nil {
		return
	}
	delete(jsonData, constant.UrlSuffixField)
	// 转发数据
	mapData := dataToMap(ruleConfig["variableMap"].(map[string]interface{}), jsonData)
	if len(mapData) > 0 {
		jsonData = mapData
	}
	// 客户端id
	clientId := enums.Mqtt.Get().Value + constant.MqttNumber + "-" + serverId.(string)
	if item, ok := clients.ForwardMqClients.Load(clientId); ok && item != nil {
		clientItem := item.(*mq.Client)
		contentBytes, _ := json.Marshal(jsonData)
		err := clientItem.Publish(forwardTopic, contentBytes)
		if err == nil {
			_ = env.Cache.HashSet(constant.ForwardClientPrefix+serverId.(string), map[string]interface{}{constant.ForwardClientLastTime: utils.GetNowTimeStr()})
			_, _ = env.Cache.HIncrBy(constant.ForwardClientPrefix+serverId.(string), constant.ForwardClientSendCount, 1)
			logger.Debugf("mqtt数据转发成功 topic=[%+v] clientId=[%+v]", forwardTopic, clientId)
			addToDetail(serverId.(string))
		}
	} else {
		logger.Errorf("mqtt数据转发客户端失效 clientId=[%+v]", clientId)
	}
}
